const path = require("path");
const { sep } = path;
const glob = require("glob");
// 匹配当前目录及其子目录下的所有.js文件，并将匹配到的文件路径打印出来‌

/**
 * extend loader
 * @param {object} app Koa  实例
 * 加载所有extend 可以通过 'app.extend.${目录}.${文件}' 访问
 * 
  例子 app/extend
   |
            | -- custom-extend.js
   => app.extend.customExtend
  */
module.exports = (app) => {
  // 读取 app/extend/**.js
  const extendPath = path.resolve(app.businessPath, `.${sep}extend`);
  const fileList = glob.sync(path.resolve(extendPath, `.${sep}**${sep}**.js`));
  // 遍历所有的文件目录 把内容加载到app.extend下
  fileList.forEach((file) => {
    // 获取文件名称
    let name = path.resolve(file);
    name = name.substring(
      name.lastIndexOf(`extend${sep}`) + `extend${sep}`.length,
      name.lastIndexOf(".")
    ); // 把 '-'统一改为驼峰 custom-module/custom-middleware =>customModule.customMiddleware
    name = name.replace(/[_-][a-z]/gi, (s) => s.substring(1).toUpperCase());
    // 过滤app已经存在的key
    for (const key in app) {
      if (key == name) {
        console.log(`[extend load error] name: ${name} is already in app `);
        return;
      }
    }
    app[name] = require(path.resolve(file))(app);
  });
};
